package com.alibaba.csp.sentinel.dashboard.rule.apollo;

import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang.StringUtils;

import com.ctrip.framework.apollo.openapi.client.ApolloOpenApiClient;

public final class ApolloConfigUtil {

	private static final String FLOW_RULE_TYPE = "flow";
	
	private static final String DEGRADE_RULE_TYPE = "degrade";
	//  *-flow-rules
    private static final String FLOW_DATA_ID_POSTFIX = "-" + FLOW_RULE_TYPE + "-rules";
    //  *-degrade-rules
    private static final String DEGRADE_DATA_ID_POSTFIX = "-" + DEGRADE_RULE_TYPE + "-rules";
	
    private static ConcurrentHashMap<String, ApolloOpenApiClient> APOLLOOPENAPICLIENTMAP = new ConcurrentHashMap<>();
    
    
    // apollo-test-flow-rules
    public static String getFlowDataId(String appName) {
        return String.format("%s%s", appName, FLOW_DATA_ID_POSTFIX);
    }
    // apollo-test-degrade-rules
    public static String getDegradeDataId(String appName) {
        return String.format("%s%s", appName, DEGRADE_DATA_ID_POSTFIX);
    }
    
    public static ApolloOpenApiClient createApolloOpenApiClient(String appName) {
    	ApolloOpenApiClient client = APOLLOOPENAPICLIENTMAP.get(appName);
    	if(client != null) {
    		return client;
    	} else {
    		String token = ApolloConfig.tokenMap.get(appName);
    		if(StringUtils.isNotBlank(token)) {
    			client = ApolloOpenApiClient
    					.newBuilder()
    					.withPortalUrl(ApolloConfig.URL)
    					.withToken(token)
    					.build();
    			APOLLOOPENAPICLIENTMAP.putIfAbsent(appName, client);
    			return client;
    		} else {
    			System.err.println("根据指定的appName:"+ appName + ", 找不到对应的token");
    			return null;
    		}
    	}
    }
    
    
	public static String getAppIdWithAppName(String appName) {
		return ApolloConfig.appIdMap.get(appName);
	}
    
}
